package com.cyy.springbootinit.mq;

import com.cyy.springbootinit.model.dto.message.PaymentMessage;
import com.cyy.springbootinit.model.entity.*;
import com.cyy.springbootinit.model.enums.EquipmentTypeConst;
import com.cyy.springbootinit.service.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;

@Component
@Slf4j
public class PaymentMessageConsumer {

    @Resource
    private BalanceAlarmService balanceAlarmService;
    
    @Resource
    private BalanceWarningService balanceWarningService;
    
    @Resource
    private PaymentBillService paymentBillService;
    
    @Resource
    private EquipmentInfoService equipmentInfoService;

    @RabbitListener(queues = "payment.queue")
    public void handlePaymentMessage(PaymentMessage message) {
        log.info("收到支付消息：{}", message);
        try {
            // 处理报警信息
            QueryWrapper<BalanceAlarm> queryWrapper1 = new QueryWrapper<>();
            LocalDate today = LocalDate.now();
// 如果 startDate 为空，设置为昨天（当前日期 - 1 天）
            LocalDate yesterday = today.minusDays(1); // 昨天
            Date startDate = Date.from(yesterday.atStartOfDay(ZoneId.systemDefault()).toInstant()); // 转换为 Date 类型
            queryWrapper1.eq("equipmentId", message.getEquipmentId()).gt("alarmDate",startDate);
            BalanceAlarm balanceAlarm = balanceAlarmService.getOne(queryWrapper1);
            EquipmentInfo equipmentInfo = null;
            
            if(balanceAlarm != null && balanceAlarm.getIsSolved() == 0) {
                equipmentInfo = equipmentInfoService.getById(message.getEquipmentId());
                String text = EquipmentTypeConst.getEnumByValue(equipmentInfo.getTypeName()).getText();
                
                QueryWrapper<BalanceWarning> queryWrapper2 = new QueryWrapper<>();
                queryWrapper2.eq("warningType", text);
                BalanceWarning balanceWarning = balanceWarningService.getOne(queryWrapper2);
                
                if(balanceAlarm.getDeviceBalance() + message.getMoney() >= balanceWarning.getThresholdValue()) {
                    balanceAlarm.setIsSolved(1);
                    balanceAlarm.setNote("已支付" + message.getMoney() + "元");
                }
                //修改设备通知
                String str = balanceAlarm.getNote();
                int l=0,r=0;
                for(int i=0;i<str.length();i++){
                    if(str.charAt(i)=='值') l=i;
                    else if(str.charAt(i)=='元') r=i;
                }
                String ans=str.substring(l+1,r);
                balanceAlarm.setNote(str.substring(0,l+1)+(Double.parseDouble(ans)-message.getMoney())+"元");
                //balanceAlarm.setNote("余额不足请至少充值"+(balanceAlarm.getDeviceBalance()-message.getMoney())+"元");
                balanceAlarm.setDeviceBalance(balanceAlarm.getDeviceBalance() + message.getMoney());
                balanceAlarmService.updateById(balanceAlarm);
            }

            // 记录支付历史
            PaymentBill paymentBill = new PaymentBill();
            paymentBill.setPaymentAmount(message.getMoney());
            paymentBill.setUserId(message.getUserId());
            paymentBill.setDormitoryId(message.getDormitoryId());
            
            if(equipmentInfo == null) {
                QueryWrapper<EquipmentInfo> queryWrapper3 = new QueryWrapper<>();
                queryWrapper3.eq("equipmentId", message.getEquipmentId());
                equipmentInfo = equipmentInfoService.getOne(queryWrapper3);
            }
            
            paymentBill.setPaymentPurpose(EquipmentTypeConst.getEnumByValue(equipmentInfo.getTypeName()).getText());
            paymentBillService.save(paymentBill);
            
        } catch (Exception e) {
            log.error("处理支付消息失败", e);
            // 可以考虑重试机制
        }
    }
} 